package com.ywx.yypicturebackend.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.ywx.yypicturebackend.annotation.AuthCheck;
import com.ywx.yypicturebackend.common.BaseResponse;
import com.ywx.yypicturebackend.common.DeleteRequest;
import com.ywx.yypicturebackend.common.ResultUtils;
import com.ywx.yypicturebackend.constant.UserConstant;
import com.ywx.yypicturebackend.exception.BusinessException;
import com.ywx.yypicturebackend.exception.ErrorCode;
import com.ywx.yypicturebackend.exception.ThrowUtils;
import com.ywx.yypicturebackend.model.dto.space.SpaceAddRequest;
import com.ywx.yypicturebackend.model.dto.space.SpaceEditRequest;
import com.ywx.yypicturebackend.model.dto.space.SpaceQueryRequest;
import com.ywx.yypicturebackend.model.dto.space.SpaceUpdateRequest;
import com.ywx.yypicturebackend.model.entity.Space;
import com.ywx.yypicturebackend.model.entity.User;
import com.ywx.yypicturebackend.model.enums.SpaceLevelEnum;
import com.ywx.yypicturebackend.model.vo.SpaceLevel;
import com.ywx.yypicturebackend.model.vo.SpaceVO;
import com.ywx.yypicturebackend.service.SpaceService;
import com.ywx.yypicturebackend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@RestController
@Slf4j
@RequestMapping("/space")
public class SpaceController {


    @Resource
    private SpaceService spaceService;

    @Resource
    private UserService userService;

    @Resource
    private TransactionTemplate transactionTemplate;


    @PostMapping("/add")
    public BaseResponse<Long> addSpace(@RequestBody SpaceAddRequest spaceAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(spaceAddRequest == null, ErrorCode.PARAMS_ERROR);

        User loginUser = userService.getLoginUser(request);

        long spaceId = spaceService.addSpace(spaceAddRequest, loginUser);

        return ResultUtils.success(spaceId);

    }

    ;


    /**
     * 删除空间
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteSpace(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        User loginUser = userService.getLoginUser(request);
        long id = deleteRequest.getId();

        //判断是否存在
        Space oldSpace = spaceService.getById(id);
        ThrowUtils.throwIf(oldSpace == null, ErrorCode.PARAMS_ERROR);
        //仅本人或者管理员可以删除
        spaceService.checkSpaceAuth(oldSpace, loginUser);

        transactionTemplate.execute(status -> {
            //联合把空间中的图片也删除
            spaceService.deletePictureBySpaceId(oldSpace.getId());
            //删除空间
            boolean deleteResult = spaceService.removeById(id);
            ThrowUtils.throwIf(!deleteResult, ErrorCode.OPERATION_ERROR);

            return true;
        });


        return ResultUtils.success(true);

    }


    /**
     * 更新空间数据,仅管理员可以,一些简单的逻辑可以不用封装到Service层直接写在Controller层
     *
     * @param updateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateSpace(@RequestBody SpaceUpdateRequest updateRequest,
                                             HttpServletRequest request) {

        if (updateRequest == null || updateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //判断是否存在
        long id = updateRequest.getId();
        Space oldSpace = spaceService.getById(id);
        ThrowUtils.throwIf(oldSpace == null, ErrorCode.PARAMS_ERROR);

        //DTO =》 实体类
        Space space = new Space();
        BeanUtils.copyProperties(updateRequest, space);

        //校验数据是否合法
        spaceService.validSpace(space, false);

        //填充空间等级相关数据
        spaceService.fillSpaceBySpaceLevel(space);


        //更新数据
        boolean result = spaceService.updateById(space);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }


    /**
     * 根据id获取空间的所有信息,仅管理员可用
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Space> getSpaceById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        Space space = spaceService.getById(id);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(space);
    }

    /**
     * 根据id获取空间封装类
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<SpaceVO> getSpaceVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);

        Space space = spaceService.getById(id);

        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(spaceService.getSpaceVO(space, request));
    }

    /**
     * 获取空间分页列表,仅管理员可用
     *
     * @param spaceQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Space>> listSpaceByPage(@RequestBody SpaceQueryRequest spaceQueryRequest) {
        long current = spaceQueryRequest.getCurrent();
        long pageSize = spaceQueryRequest.getPageSize();


        Page<Space> spacePage = spaceService.page(new Page<>(current, pageSize),
                spaceService.getQueryWrapper(spaceQueryRequest));

        return ResultUtils.success(spacePage);
    }

    /**
     * 分页获取空间列表（封装类）
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<SpaceVO>> listSpaceVOByPage(@RequestBody SpaceQueryRequest spaceQueryRequest,
                                                         HttpServletRequest request) {
        long current = spaceQueryRequest.getCurrent();
        long size = spaceQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);


        // 查询数据库
        Page<Space> spacePage = spaceService.page(new Page<>(current, size),
                spaceService.getQueryWrapper(spaceQueryRequest));
        // 返回封装类
        return ResultUtils.success(spaceService.getSpaceVOPage(spacePage, request));
    }


    /**
     * 用户编辑空间
     *
     * @param spaceEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editSpace(@RequestBody SpaceEditRequest spaceEditRequest, HttpServletRequest request) {
        if (spaceEditRequest == null || spaceEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        Space space = new Space();
        BeanUtils.copyProperties(spaceEditRequest, space);


        //设置编辑时间
        space.setEditTime(new Date());
        //数据校验
        spaceService.validSpace(space, false);
        //判断空间是否存在
        Long id = spaceEditRequest.getId();
        Space oldSpace = spaceService.getById(id);
        ThrowUtils.throwIf(oldSpace == null, ErrorCode.NOT_FOUND_ERROR);

        //获取当前登录用户
        User loginUser = userService.getLoginUser(request);

        //仅本人或管理员可编辑空间
        spaceService.checkSpaceAuth(oldSpace, loginUser);

        //填充空间等级属性
        space.setSpaceLevel(oldSpace.getSpaceLevel());
        spaceService.fillSpaceBySpaceLevel(space);


        //操作数据库
        boolean result = spaceService.updateById(space);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);

        return ResultUtils.success(true);
    }


    /**
     * 获取所有空间级别信息
     *
     * @return
     */
    @GetMapping("/list/level")
    public BaseResponse<List<SpaceLevel>> listSpaceLevel() {

        List<SpaceLevel> spaceLevelList = Arrays.stream(SpaceLevelEnum.values()).map(spaceLevelEnum -> {
            return new SpaceLevel(spaceLevelEnum.getLevel(),
                    spaceLevelEnum.getContext(), spaceLevelEnum.getMaxCount(), spaceLevelEnum.getMaxSize());
        }).collect(Collectors.toList());

        return ResultUtils.success(spaceLevelList);
    }


}
